using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrinting.Native.WinControls;
using DevExpress.XtraReports.UI;
using System.Windows.Forms;

namespace RitaReports
{
    public partial class XtraReportViewer : XtraUserControl
    {
        private XtraReport report = new XtraReport();
        private BrickPagePair _markedBrick;

        public XtraReport Reports
        {
            get
            {
                return report;
            }
            set
            {
                report = value;
                printBarManager1.BeginUpdate();
                printControl1.PrintingSystem = (report != null) ? report.PrintingSystem : null;
                printBarManager1.EndUpdate();
            }
        }

        public XtraReportViewer()
        {
            InitializeComponent();
        }

        public void SelectByBookmark(BookmarkNode bookmark)
        {
            if (_markedBrick != null)
            {
                _markedBrick.Page.Document.PrintingSystem.UnmarkBrick(_markedBrick.Brick, _markedBrick.Page);
                _markedBrick = null;
            }

            if (bookmark != null)
            { 
                bookmark.ShowAssociatedBrick(printControl1);
                bookmark.Page.Document.PrintingSystem.MarkBrick(bookmark.Brick, bookmark.Page);
                _markedBrick = bookmark.Pair;
            }

            printControl1.UpdatePageView();
        }

        private void printControl1_ControlAdded(object sender, ControlEventArgs e)
        {
            if (HasBookmarksView(e.Control))
            {
                e.Control.Visible = false;
            }
        }

        bool HasBookmarksView(Control control)
        {
            if (control is BookmarkTreeView)
            {
                return true;
            }

            foreach (Control child in control.Controls)
            {
                if (HasBookmarksView(child))
                {
                    return true;
                }
            }

            return false;
        }
    }
}
